import { leftMenu } from '@/api/manager'
import { constantRoutes } from '@/router'
import { generateAsyncRoutes } from '@/utils/async-routes'

const getDefaultState = () => {
  return {
    routes: null,
    originRoutes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ROUTES: (state, routes) => {
    state.routes = constantRoutes.concat(routes)
  },
  SET_ORIGIN_ROUTES: (state, originRoutes) => {
    state.originRoutes = originRoutes
  },
}

const actions = {
  getAsyncRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      leftMenu().then(response => {
        const { data } = response
        const asyncRoutes = generateAsyncRoutes(data)
        // 最后追加这个
        asyncRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', asyncRoutes)
        commit('SET_ORIGIN_ROUTES', data)
        resolve(asyncRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

